<?php 
namespace Admin\Controller;
use \Think\Controller;

class CategoryController extends Controller{

	protected $catModel = null;
	protected $data = null;

	public function __construct(){

		parent::__construct();

		$this->catModel = D('category');
		$this->data = $this->catModel->getCats();
	}

	public function cat_add(){
			
		//判断 请求是GET 还是 POST
		if(IS_POST){

			if($this->catModel->create(I('post.')))
			{


				//调用模型
				if($this->catModel->add())
				{

					$this->success('添加成功',U('cat_list'));
					exit;
				}

				$this->error($this->catModel->getError());
				exit;
				
			}

				$this->error($this->catModel->getError());
		
		}

		
		$catlist = $this->catModel->getTree($this->data);
		$this->assign('catlist',$catlist);

		$this->display();
	}
	public function cat_edit()
	{	
		$cat_id = I('get.cat_id');
		//判断提交方式是GET还是POST
		if(IS_POST)
		{	
		
			if($this->catModel->create(I('post.'))&& !empty(I('post.cat_name')))
			{	

				$data = $this->catModel->getSonID($this->data,$cat_id);

				//当前节点的子栏目 不能被修改为其父节点
				if(!in_array(I('post.parent_id'),$data))
				{			
				
					if($this->catModel->save())
					{

						$this->success('修改成功',U('cat_list'));
						exit;
						
					}
					else
					{
				 		 $this->error($this->catModel->getError());
				  		 exit;
					}

				}
				 $this->error('上级栏目设置有误');
				exit;	
			}

			$this->error($this->catModel->getError());
		}
		$catInfo = $this->catModel->find($cat_id);
		$this->assign($catInfo);
		
		$catlist = $this->catModel->getTree($this->data);
		$this->assign('catlist',$catlist);
		$this->display();
	}
	public function cat_list()
	{	
		$catlist = $this->catModel->getTree($this->data);
		$this->assign('catlist',$catlist);
		$this->display();
	}

	public function cat_delete()
	{
		$cat_id = I('get.cat_id');
		$catlist = $this->catModel->getTree($this->data,$cat_id);


		if(!empty($catlist))
		 {
			echo '不能删除父栏目';
		 }
		 else
		 {
		 	echo  $this->catModel->delete($cat_id)?'delet eok':'delete fail';	  		
		 }

	}
/*
	public function test()
	{
			print_r($this->catModel->getSonID($this->data,1));
	}*/
}
 ?>